package top.oneit.jdownload;

import javafx.application.Application;
import javafx.stage.Stage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import top.oneit.jdownload.config.ApplicationConfig;
import top.oneit.jdownload.config.DbConfig;
import top.oneit.jdownload.data.dao.AppLogDao;
import top.oneit.jdownload.data.entity.AppLog;
import top.oneit.jdownload.stages.HomeStage;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class JdownloadApplication extends Application {
    public static ConcurrentMap<String, Stage> stages = new ConcurrentHashMap<>();
    public static SessionFactory sessionFactory;
    // 缓存
    public static ConcurrentMap<String,Object> cache=new ConcurrentHashMap<>();

    @Override
    public void start(Stage primaryStage) throws Exception {
        sessionFactory = DbConfig.init();

        // init config
        ApplicationConfig.init(sessionFactory.getCurrentSession());

        // add up log
        AppLog log = new AppLog();
        log.setContent("up");
        AppLogDao.save(log);
        // 主页
        new HomeStage();
    }

    public static void main(String[] args) {
        // 捕捉未处理的异常
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("捕捉到未处理的异常：" + e.getMessage());
                // 抛出栈信息
                e.printStackTrace();
            }
        });
        launch(args);
    }

    @Override
    public void init() throws Exception {
    }

    @Override
    public void stop() throws Exception {
        Session currentSession = sessionFactory.getCurrentSession();
        currentSession.beginTransaction();
        AppLog log = new AppLog();
        log.setContent("stop");
        currentSession.save(log);
        currentSession.getTransaction().commit();
    }

    /**
     * 获取对象,,注意返回空值
     */
    public static  <T> T getStage(Class<T> clazz) {
        Stage stage = stages.get(clazz.getName());
        if (stage == null)
            return null;
        return (T) stages.get(clazz.getName());
    }
}
